<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%String path = request.getContextPath();%>
<%@ taglib uri="/WEB-INF/tld/c.tld" prefix="c" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>保单结算记录 管理</title>
    <style type="text/css">
        .searchArea .fieldBox .label{width: 70px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis;}
    </style>
    <jsp:include page="../../import.jsp" flush="true"/>
</head>

<body class="iframeBody">
	<div class="Wrapper">
         <div class="searchArea">
            <form id="searchBar">
                <div class="fieldset1 clearFix">
                    <div class="fieldBox">
                        <div class="label">结算单号</div>
                        <div class="field">
                            <input name="stlNo" id="stlNo" type="text" class="ui-textbox" value="">
                        </div>
                    </div>
                    <div class="fieldBox">
                        <div class="label">保险支公司</div>
                        <div class="field">
                            <input name="insCompNm" id="insCompNm" value="" class="ui-textbox">
                        </div>
                    </div>
                    <div class="fieldBox">
                        <div class="label">结算日期</div>
                        <div class="field">
                            <input ligerui="width:82" name="stlBgTm" id="stlBgTm" type="text" class="ui-datepicker" value="">
                            -
                            <input ligerui="width:82" name="stlEndTm" id="stlEndTm" type="text" class="ui-datepicker" value="">
                        </div>
                    </div>
                    <div class="fieldBox">
                        <div class="label">结算状态</div>
                        <div class="field">
                            <input name="stlStsCd" id="stlStsCd" data-value="" placeholder="请选择" ltype="combobox">
                        </div>
                    </div>

                    <div class="formBtns notRight">
                        <span id="searchBtn" class="sq-button sq-button-round">查询</span>
                        <span id="clearBtn" class="sq-button sq-button-round">清空</span>
                        <%--<span id="downloadBtn" class="sq-button sq-button-round">导出</span> --%>
                        <input id="resetBtn" type="reset" value="重置" class="l-button l-button-reset Hide"/>
                    </div>
                    <sys:funcAuth resCd="insPlcStlRecModify">
                    <div class="fieldBox">
                        <div class="field">
                            <jsp:include page="../../system/sysUlFilesRec/sysSysUlFilesRecUpload.jsp" flush="true" >
                                <jsp:param name="fileNum" value="1"/>
                                <jsp:param name="filePath" value="insurance/insPlcStlRec"/>
                            </jsp:include>
                        </div>
                        <div class="field">
                            <span id="addBatchBtn" class="sq-button sq-button-round" onclick="addBatch();">导入结算</span>
                            <!-- <span id="downTempBtn" class="sq-button sq-button-round" onclick="downTemp();">下载模板</span> -->
                        </div>
                    </div>
                </sys:funcAuth>
                </div>
            </form>
		</div>
		<div id="ligergrid1" class="sq-grid"></div>
	</div>

<script type="text/javascript">
    var grid = null, menu = null;
    var detailGrid = null;
    $(function() {
    	grid = $("#ligergrid1").ligerGrid({
    		url: '<%=path%>/insurance/insPlcStl/initStlRecList.do',
            method: 'get',
            columns: [
				{display: '结算单号', name: 'stlNo', width: 150, align: 'left', enabledSort: true},
				{display: '保险支公司名称', name: 'insCompNm', minWidth: 150, align: 'left', enabledSort: true},
				{display: '保费金额', name: 'insFee', minWidth: 100, align: 'right', enabledSort: true,
                    render:function(rowdata){
                        return '&yen;'+FormatMoney(rowdata.insFee/100);
                    }
				},
				{display: '结算金额', name: 'stlAmt', minWidth: 100, align: 'right', enabledSort: true,
                    render:function(rowdata){
                        return '&yen;'+FormatMoney(rowdata.stlAmt/100);
                    }
				},
				{display: '实际结算金额', name: 'actStlAmt', minWidth: 100, align: 'right', enabledSort: true,
                    render:function(rowdata){
                        return '&yen;'+FormatMoney(rowdata.actStlAmt/100);
                    }
                },
                {display: '结算状态', name: 'stlStsCdNm', minWidth: 100, align: 'center', enabledSort: false},
                {display: '结清时间', name: 'stlCompTm', minWidth: 90, align: 'left', enabledSort: true,render: renderDate },
                {display: '备注', name: 'stlRem', minWidth: 120, align: 'left', enabledSort: false},
				{display: '操作',  minWidth: 120, align: 'left', enabledSort: false,
					render: function (rowdata, rowindex, value)
				    {
				        var h = "";
				        if (rowdata.stlStsCd==30)//待确认
				        {
                            h='<a class="sq-button-hasicon" href="javascript:;" onclick="confrimStl(';
                            h+="'"+rowdata.id+"'," + rowdata.stlAmt + ",'" + rowdata.stlNo+"',"+ rowdata.actStlAmt;
                            h+=')"><i class="sqBtnIco_15"></i>结算</a>';
                            h+='<a class="sq-button-hasicon" href="javascript:;" onclick="cancelStl(';
                            h+="'"+rowdata.id+"'";
                            h+=')"><i class="sqBtnIco_7"></i>删除</a>';
				        }
				        return h;
				    }
				},
            ], 
            pageSize: 10,
            root: 'rows',
            record: 'total',
            hideLoadButton: true,
            width: '100%',
            height: '100%',
            heightDiff: -2,
            allowUnSelectRow:true,
            alternatingRow: false,
            onBeforeShowData: function ()
            {
                var grid = this; 
                grid.collapsedRows = [];
            },
            detail: {
                height: 'auto',
                onShowDetail: showDetail_grid
            }
        });

        grid.setHeight(100);

        $("#stlStsCd").ligerComboBox({
            valueField: 'key',
            textField: 'value'
        });
        $("#searchBar").ligerForm();
        liger.get("stlStsCd").setData(${stlStsCdList});

        $("#pageloading").hide();

        /* 查询 */
        $("#searchBtn").click(function (event) {
            var form = liger.get("searchBar");
            var data = form.getData();
            for (name in data) {
                grid.setParm(name, data[name]);
            }
            grid.reload();
        });

        /* 清空 */
        $("#clearBtn").click(function (event) {
            clearLigerForm("searchBar");
        });

        /*保存修改*/
        $("#saveBtn").click(function (event) {
            $(document).trigger('click');
            var _dtls=detailGrid.getUpdated();
            var _dtlArray = [];
            var actStlAmt=0;
            for (var index in _dtls) {
                if(!_dtls[index].actStlAmtDb){
                    actStlAmt=0;
                }else{
                    actStlAmt=parseFloat(_dtls[index].actStlAmtDb)*100;
                }
                _dtlArray.push({'id':_dtls[index].id,'actStlAmt':actStlAmt,'stlId':_dtls[index].stlId,'insPlcId':_dtls[index].insPlcId});
            }
            alert(JSON.stringify(_dtlArray));
            return;
        });

        //导出
        $("#downloadBtn").click(function (event) {
            var form = liger.get("searchBar");
            var data = form.getData();
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType:'json',
                url: '<%=path%>/insurance/insPlcStl/exportStlRecList.do',
                data:data,
                beforeSend:function(){
                    wait_dialog=$.ligerDialog.SQalert({content: '正在导出...',SQ_type: "waitting"});
                },
                success:function(msg){
                    wait_dialog.close();
                    if(msg.success == 1){
                        window.open(msg.data);
                    }else{
                        $.ligerDialog.SQalert({content:msg.info, SQ_type: "error"});
                    }
                }
            });
        });
    });
    
    /* 结算 */
    function confrimStl(id,stlAmt,stlNo,actStlAmt) {
        $.ligerDialog.open({
            cls: 'noBorder_Dialog',
            width: 500,
            height: 400,
            title: '结算确认',
            url: '<%=path%>/insurance/insPlcStl/toModifyPage.do?id=' + id+"&stlAmt="+stlAmt+"&stlNo="+stlNo+"&actStlAmt="+actStlAmt
        });
    }
    
    /* 删除 */
    function cancelStl(id) {
        var _ids = [id];
        $.ligerDialog.confirm(LogUtils.LOG_CMM_DELETE_CONFIRM, function (flag) {
            if (flag == false)return;
            var wait_dialog;
            $.ajax({
                type: 'post',
                dataType: 'json',
                data: {ids: JSON.stringify(_ids)},
                url: '<%=path%>/insurance/insPlcStl/removeByIds.do',
                beforeSend: function () {
                    wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
                },
                success: function (msg) {
                    wait_dialog.close();
                    if (msg.success == 1) {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                        grid.reload();
                    } else {
                        $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                    }
                }
            });
        });
    }

    $(document).on('click', '.saveBtn', function(event) {
        $(document).trigger('click');
        var detailGridID=$(this).parents('.l-grid-detailpanel-inner').find('[ligeruiid]').attr('ligeruiid');
        var dtlGrid = liger.get(detailGridID);

        var _dtls=dtlGrid.getUpdated();
        if (_dtls.length == 0) {
            $.ligerDialog.SQalert({content: "未找到要修改的数据", SQ_type: "warning"});
            return;
        }
        var _dtlArray = [];
        var actStlAmt=0;
        for (var index in _dtls) {
            if(!_dtls[index].actStlAmtDb){
                actStlAmt=0;
            }else{
                actStlAmt=parseFloat(_dtls[index].actStlAmtDb)*100;
            }
            _dtlArray.push({'id':_dtls[index].id,'actStlAmt':actStlAmt,'stlId':_dtls[index].stlId,'insPlcId':_dtls[index].insPlcId});
        }
        var wait_dialog;
        $.ajax({
            type: 'post',
            dataType: 'json',
            data: {dtls: JSON.stringify(_dtlArray)},
            url: '<%=path%>/insurance/insPlcStlDtl/modifyStlAmt.do',
            beforeSend: function () {
                wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
            },
            success: function (msg) {
                wait_dialog.close();
                if (msg.success == 1) {
                    $.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                    //grid.reload();
                } else {
                    $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                }
            }
        });
    });

    $(document).on('click', '.delDtlBtn', function(event) {
        $(document).trigger('click');
        var detailGridID=$(this).parents('.l-grid-detailpanel-inner').find('[ligeruiid]').attr('ligeruiid');
        var dtlGrid = liger.get(detailGridID);
        var selectedRows = dtlGrid.getSelectedRows();
        if (selectedRows.length == 0) {
            $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_SELECT_MORE_ROW, SQ_type: "warning"});
            return;
        }
        var row=grid.getRow($(this).attr('rowid'));
        var _dtlArray = [];
        for (var index in selectedRows) {
            _dtlArray.push({'id':selectedRows[index].id,'stlId':selectedRows[index].stlId,'insPlcId':selectedRows[index].insPlcId});
            row.actStlAmt-=selectedRows[index].actStlAmt;
        }

        var wait_dialog;
        $.ajax({
            type: 'post',
            dataType: 'json',
            data: {dtls: JSON.stringify(_dtlArray)},
            url: '<%=path%>/insurance/insPlcStlDtl/removeByIds.do',
            beforeSend: function () {
                wait_dialog = $.ligerDialog.SQalert({content: LogUtils.LOG_CMM_DATA_LOADING, SQ_type: "waitting"});
            },
            success: function (msg) {
                wait_dialog.close();
                if (msg.success == 1) {
                    $.ligerDialog.SQalert({content: msg.info, SQ_type: "success"});
                    //grid.reload();
                    grid.updateRow(row.__id,{
                        actStlAmt:row.actStlAmt
                    });
                    dtlGrid.deleteSelectedRow();
                } else {
                    $.ligerDialog.SQalert({content: msg.info, SQ_type: "error"});
                }
            }
        });
    });

    function showDetail_grid(row, detailPanel, callback){
        var gridBox = document.createElement('div');
        var btns='<div class="btnsBox" style="text-align: center;"><span class="sq-button sq-button-round saveBtn">修改</span><span rowid="'+row.__id+'" class="sq-button sq-button-round delDtlBtn">删除</span></div>';
        $(gridBox).css('margin', 10);
        $(detailPanel).css({
            'padding': 10,
            'box-sizing': 'border-box'
        }).append(gridBox);
        if(row.stlStsCd!=40){
            $(detailPanel).append(btns);
        }
        detailGrid = $(gridBox).ligerGrid({
        	url: '<%=path%>/insurance/insPlcStlDtl/initDtlList.do?stlId='+row.id,
            method: 'get',
            columns: [
				{display: '保单号', name: 'plcNo', minWidth: 160, align: 'left',
                    render: function (rowdata, index, value) {
                        if(!value||value==null||value=='null'){
                            return '<a href="javascript:;" onclick="queryPlcDtl('+rowdata.insPlcId+')">保单</a>';
                        }
                        return '<a onclick="queryPlcDtl(' + rowdata.insPlcId + ');">' + rowdata.plcNo + '</a>';
                    }
                },
				{display: '购买方式', name: 'buyWayCdNm', minWidth: 100, align: 'left'},
				{display: '保险种类', name: 'insTypCdNm', minWidth: 100, align: 'left'},
				{display: '起保日期', name: 'insBgTm', minWidth: 100, align: 'center',render:renderDate},
				{display: '止保日期', name: 'insEndTm', minWidth: 100, align: 'center',render:renderDate},
				{display: '应结算金额', name: 'stlAmt', minWidth: 100, align: 'right',
                     render:function(rowdata,rowid,value){
                         if(rowdata.insFee){
                            return '&yen;'+FormatMoney(rowdata.stlAmt/100);
                         }
                     }
				},
				{display: '实际结算金额', name: 'actStlAmtDb', minWidth: 100, align: 'right',
                    editor: {type: 'number',precision: 2,toFix: true,
                        onToFix: function () {
                            $.ligerDialog.SQalert({
                                SQ_type: "warning",
                                content: "小数点后面最多2位！"
                            });
                        }
                    },
                    render:function(rowdata,rowid,value){
                        if(rowdata.actStlAmtDb){
                            return '&yen;'+FormatMoney(rowdata.actStlAmtDb);
                        }
                    }
                },
            ],
            onBeforeSubmitEdit: function (e) {
                if (e.column.columnname == "actStlAmtDb") {
                    var amt=row.actStlAmt+parseFloat(e.value)*100-e.record.actStlAmt;
                    e.record.actStlAmt=parseFloat(e.value)*100;
                    grid.updateRow(row.__id,{
                        actStlAmt:amt
                    });
                }
            },
            root: 'rows',
            hideLoadButton : true,
            width: '100%',
            height: 'auto',
            isScroll: false,
            rownumbers:true,  //显示序号
            allowUnSelectRow:true,
            checkbox: true,
            alternatingRow: false,
           	onAfterShowData: callback,
            frozen: false,
            usePager: false,
            enabledEdit:true
        });
    }

    function unselectGrid (gridPanels) {
        gridPanels.each(function(index, el) {
            var detailGrid_Id=$(this).find('.l-panel').attr('ligeruiid');
            if (detailGrid_Id) {
                var detail_grid = liger.get(detailGrid_Id);
                var selectedRow_4DetailGrid = detail_grid.getSelectedRow();
                if (selectedRow_4DetailGrid) detail_grid.unselect(selectedRow_4DetailGrid);
            }
        });
    }

    //格式化时间
    function renderDate(rowdata, index, value) {
        var dateStr = "";
        if (null != value) {
            var date = new Date(value);
            dateStr = DateUtils.formatDate(date, DateUtils.YYYY_MM_DD);
        }
        return dateStr;
    }
    
    function formatActStlAmt(rowdata, index, num){
    	if (!num) return "";
    	formatCurrency(rowdata, index, num);
    }

    function queryPlcDtl(id) {
        Add_navTab('InsPlcBscInfo_DTL_' + id, "保单详情", '<%=path%>/insurance/insPlcBscInfo/toDetailPage.do?id=' + id, null);
    }

    /**
     * 格式化金额
     */
    function formatCurrency(rowdata, index, num) {
        if (!num) return "0.00";
        num = num.toString().replace(/\$|\,/g, '');
        if (isNaN(num))
            num = "0.00";
        sign = (num == (num = Math.abs(num)));
        num = Math.floor(num + 0.50000000001);
        cents = num % 100;
        num = Math.floor(num / 100).toString();
        if (cents < 10)
            cents = "0" + cents;
        for (var i = 0; i < Math.floor((num.length - (1 + i)) / 3); i++)
            num = num.substring(0, num.length - (4 * i + 3)) + ',' +
                    num.substring(num.length - (4 * i + 3));
        return (((sign) ? '' : '-') + '' + num + '.' + cents);
    }
    //导入保单结算记录
    function addBatch(){
        //获取上传文件地址
        var files=getUploadResultParams();
        //var files=[{filePath:'E:/insurance/JSJL1489543615892.xlsx'}];
        if(files&&files.length>0){
            var filePath=files[0].filePath;
            var fileExtension = filePath.substring(filePath.lastIndexOf('.') + 1);
            if(fileExtension!='xlsx'&&fileExtension!='XLSX'){
                $.ligerDialog.SQalert({content: "请上传.xlsx后缀的保单结算记录文件", SQ_type: "warn"});
                return;
            }
            $.ligerDialog.open({
                cls: 'noBorder_Dialog',
                width: 1000,
                height: 500,
                title: '保单结算记录导入数据',
                url: '<%=path%>/insurance/insPlcStl/toInsPlcStlRecImportPage.do?filePath=' +files[0].filePath
            });
        }else{
            $.ligerDialog.SQalert({content: "请先上传保单结算记录文件", SQ_type: "warn"});
        }
    }
</script>

</body>
</html>
